<?php
session_start();
include("config.php");

header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
$error = null;
# print_r($_SERVER);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
   // username and password sent from form 

   $myusername = mysqli_real_escape_string($db, $_POST['username']);
   $pwhash = hash('sha512', $_POST['password'], false);

   $mypassword = mysqli_real_escape_string($db, $pwhash);
   $sql = "SELECT id,name,last_task,level FROM user WHERE name = ? and pass = ?";
   if (!$result = get_db_result($db, $sql, "ss", $myusername, $mypassword))
      die(mysqli_error($db));
   $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
   

   $count = mysqli_num_rows($result);

   // If result matched $myusername and $mypassword, table row must be 1 row
   if ($count == 1) {
      $level = $row['level'];
      //Level 0 means user is locked out
      if ($level < 1) {
         //Log attempt
         if (!log_connection($db, true))
            exit();
         error_log("Gesperrter Nutzer " . $row['name'] . "(" . $row['id'] . " versucht login von IP: " . $_SERVER['REMOTE_ADDR'] . ", Forwarded:" . get_safe_servervar('HTTP_X_FORWARDED_FOR'));
         $_SESSION['msg'] = "Ihr Zugang ist gesperrt";
         $_SESSION['msgtype'] = "error";
      } else {
         $_SESSION['userid'] = $row['id'];
         $_SESSION['username'] = $row['name'];
         $_SESSION['userlevel'] = $level;
         //Update user.last_login
         $sql = "Update user set last_login = NOW() WHERE id = ?";
         if (!$result = get_db_result($db, $sql, "i", $row['id']))
            die(mysqli_error($db));

         //Select last project and customer if user.last_task is set
         if (isset($row['last_task']) && $row['last_task'] != null) {
            $_SESSION['lasttask'] = $row['last_task'];
            $sql = "SELECT p.customer_id AS customer_id, t.project_id AS project_id FROM task t INNER JOIN project p ON t.project_id = p.id WHERE t.id = ?";
            if (!$result = get_db_result($db, $sql, "i", $_SESSION['lasttask']))
               die(mysqli_error($db));
            $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
            $_SESSION['lastcustomer'] = $row['customer_id'];
            $_SESSION['lastproject'] = $row['project_id'];
         } else {
            //Otherwise get first that is not retired
            $sql = "SELECT min(c.id) AS cid, min(p.id) as pid, min(t.id) as tid FROM customer c INNER JOIN project p ON p.customer_id = c.id INNER JOIN task t ON t.project_id = p.id WHERE t.retired is null and p.retired is null and c.retired is null";
            if (!$result = get_db_result($db, $sql, null))
               die(mysqli_error($db));
            $row = mysqli_fetch_array($result, MYSQLI_ASSOC);

            $_SESSION['lastcustomer'] = $row['cid'];
            $_SESSION['lastproject'] = $row['pid'];
            $_SESSION['lasttask'] = $row['tid'];
         }
         //Get Screen size from hidden input at login
         //Screen size is needed for Scrollareas in tables(where height can not be set in % without bad behavior)
         $_SESSION['swidth'] = isset($_POST['swidth']) ? $_POST['swidth'] : 0;
         $_SESSION['sheight'] = isset($_POST['sheight']) ? $_POST['sheight'] : 0;

         header("Location: maintime.php");
         exit();
      }
   } else {
      //Log attempt
      if (!log_connection($db, true))
         exit();
      error_log("Fehlgeschlagener Login-Versuch. Username: " . $myusername . ", IP: " . $_SERVER['REMOTE_ADDR'] . ", Forwarded:" . get_safe_servervar('HTTP_X_FORWARDED_FOR'));
      $_SESSION['msg'] = "Name oder Passwort ist falsch";
      $_SESSION['msgtype'] = "error";
   }
} else {
   if (!log_connection($db, false))
      exit();
}
?>
<html>

<head>
   <title>Easy Time Tracker Login</title>
   <link rel="stylesheet" href="/timetracker.css" type="text/css" media="screen" />
</head>

<body>
   <div align="center">
      <div class="Login" style="width:300px; border: solid 1px #333333; " align="left">
         <div id="header"><b>Easy Time Tracker Login</b></div>

         <div style="margin:30px">

            <form action="" method="post" autocomplete="off">
               <label><?php ELang("username"); ?>:</label><br><input type="text" name="username" class="box" /><br /><br />
               <label><?php ELang("pword"); ?> :</label><br><input type="password" name="password" class="box" /><br /><br />
               <input type="hidden" id="swidth" name="swidth">
               <input type="hidden" id="sheight" name="sheight">
               <input type="submit" value=" <?php ELang("login"); ?> " /><br />
            </form>
            <script type="text/javascript">
               //Fill hidden Screen size input fields
               var widthfield = document.getElementById("swidth");
               var heightfield = document.getElementById("sheight");
               widthfield.value = screen.availWidth;
               heightfield.value = screen.availHeight
            </script>

            <?php
            if (isset($_SESSION['msg'])) {
               echo ("<div style=\"background: black\">");
               if (isset($_SESSION['msgtype'])) {
                  echo ("<div class=" . $_SESSION['msgtype'] . ">" . $_SESSION['msg'] . "</div>");
                  unset($_SESSION['msgtype']);
               } else
                  echo ("<div class=\"msg\" >" . $_SESSION['msg'] . "</div>");
               unset($_SESSION['msg']);
               echo ("</div>");
            }
            ?>


         </div>

      </div>

   </div>

</body>

</html>